/********************************************************************* 
The Freebase api contains all the core javascript functions needed 
    to retieve and send data to freebase.
**********************************************************************/


function jsonp_search_freebase(freebase_domain, name, type, success_function, error_function) {
    $.ajax({
        type: "GET",
        url: 'http://' + freebase_domain + '/api/service/search',
        data: 'category=instance&disamb=1&get_all_types=0&limit=1&prefix=' + name.toLowerCase() + '&strict=1&type=' + type,
        success: success_function(m),
        error: error_function(m),
        dataType: "jsonp",
        cache: true
    });
}
function jsonp_blurb_freebase(freebase_domain, article_id, maxlength, success_function, error_function) {
    var article_id = article_id;
    //alert(article_id);
    if(true){
        $.ajax({
            type: "GET",
            url: "http://" + freebase_domain + "/api/trans/blurb" + article_id,
            data: 'maxlength='+maxlength,
            success: function(m) {
                //alert('success')
                if (m.result && m.result.body) {
                    m.article_id = article_id;
                    success_function(m)
                }
            },
            error: error_function(),
            dataType: "jsonp",
            cache: true
        });
    }
}

function jsonp_totalblurb_freebase(freebase_domain, topic_name, topic_domain, maxlength, image_function, blurb_function, error_function){
        //topic_domain = '/user/bioventurist/default_domain/science_or_technology_company'
        $.ajax({
        type: "GET",
        url: 'http://'+freebase_domain+'/api/service/search',
        data: 'category=instance&disamb=1&get_all_types=0&limit=1&prefix=' + topic_name.toLowerCase() + '&strict=1&type='+topic_domain,
        success: function(m) {
            if(!(typeof( m.result ) == 'undefined')){
                if(m.result.length>0){ 
                    if (m.result.length > 0 && m.result[0].image){
                        image_function(m);  
                       //$("#thumb").attr('src','http://'+freebase_domain+'/api/trans/image_thumb'+m.result[0].image.id)
                    }
                    var articleID = null;
                    if(m.result[0].article != null){
                        //alert(m.result[0].article.id);
                        //var articleID = '/guid/9202a8c04000641f80000000003ba046'; //amgen
                        //var articleID = '/guid/9202a8c04000641f80000000007be5a9'; //ucb
                        articleID = m.result[0].article.id;
                        jsonp_blurb_freebase(freebase_domain, articleID, maxlength, blurb_function, error_function);
                    }
                }
            }
        },
        dataType: "jsonp",
        cache: true
    });
}

function jsonp_blurb_freebase_test(freebase_domain, article_guid, maxlength, success_function, error_function) {
    var article_guid = article_guid;
    //alert(article_id);
    $.ajax({
        type: "GET",
        url: "http://" + freebase_domain + "/api/trans/blurb/guid/" + article_guid,
        data: 'maxlength='+maxlength,
        success: function(m) {
            //alert('success')
            if (m.result && m.result.body) {
                m.article_guid = article_guid;
                success_function(m)
            }
        },
        error: function(m) {
            error_function(m)
        },
        dataType: "jsonp",
        cache: true
    });
}

function jsonp_totalblurb_freebase_test(guid, freebase_domain, topic_name, topic_domain, maxlength, image_function, blurb_function, error_function){
        guid = guid.replace(/#/,"");
        jsonp_blurb_freebase(freebase_domain, guid, maxlength, blurb_function, error_function);
        //topic_domain = '/user/bioventurist/default_domain/science_or_technology_company'
        /*
        $.ajax({
        type: "GET",
        url: 'http://'+freebase_domain+'/api/service/search',
        data: 'category=instance&disamb=1&get_all_types=0&limit=1&prefix=' + topic_name.toLowerCase() + '&strict=1&type='+topic_domain,
        success: function(m) {
            if(!(typeof( m.result ) == 'undefined')){ 
                if (m.result.length > 0 && m.result[0].image){
                    image_function(m);  
                   //$("#thumb").attr('src','http://'+freebase_domain+'/api/trans/image_thumb'+m.result[0].image.id)
                }
                var articleID = null;
                if(m.result[0].article != null){
                    //alert(m.result[0].article.id);
                    //var articleID = '/guid/9202a8c04000641f80000000003ba046'; //amgen
                    //var articleID = '/guid/9202a8c04000641f80000000007be5a9'; //ucb
                    articleID = m.result[0].article.id;
                    jsonp_blurb_freebase(freebase_domain, articleID, maxlength, blurb_function, error_function);
                }
            }
        },
        dataType: "jsonp",
        cache: true
    });
    */
}
/*
function x(i,j,t,name, topic, table, maxlength) {
    jsonp_totalblurb_freebase('{{ domain_used }}', name, topic, maxlength, 
        function(m){
        },
        function(m){
            t.setCell(parseFloat(i), j, m.result.body);
            table.draw(t, {allowHtml: true});           
        },
        function(m){} 
);
}
*/
/*
function x(i,j,t,name, topic, table, maxlength) {
    jsonp_totalblurb_freebase('{{ domain_used }}', name, topic, maxlength, 
        function(m){
        },
        function(m){
            t.setCell(parseFloat(i), j, m.result.body);
            table.draw(t, {allowHtml: true});           
        },
        function(m){} 
);
}
*/

function perform_freebase_read(url, query, success_function, error_function) {

    $.ajax({
            type: "GET",
            url: url,
            data: "query="+query,
            success: success_function,
            error: error_function,
            dataType: "jsonp",
            timeout: 20*1000,
            cache: false
    });
}

function perform_freebase_read_noasync(url, query, success_function, error_function) {
    $.ajax({
            type: "GET",
            url: url,
            async: false,
            data: "query="+query,
            success: success_function,
            error: error_function,
            dataType: "jsonp",
            cache: false
    });
}

function split_numbers(num) {
    var sign = '';
    var number = '';
    var inc = 1;
    var digits = "";
    num = num + "";

    if (num.indexOf('.') > 0) {
        digits = num.substring(num.indexOf('.'));
        num = num.substring(0,num.indexOf('.'));
    }
    
    if (num < 0) {
        sign = "-"
    }
    for (var i = num.length -1; i >= 0; i--) {
        number = num.charAt(i) + "" + number;
        if (inc == 3 && i > 0) {
            inc = 1;
            number = "," + number;
        } else {inc++;}
    }
    return number;
}

//var _mw_set_ = false;

function perform_touch(freebase_domain) {
  //if (!_mw_set_) {
  $.ajax({
    type: "GET",async:'false',
    dataType: "jsonp",    
    url: 'http://' + freebase_domain + '/api/service/touch' ,
    success: function (msg) { 
        //alert('Touch a Success')
        var test = true; 
        },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        //alert('Touch a Failure')
    }
  });
}

function createFreebaseRedirect(guid, html_id){
    guid = guid.replace ("#","");
    var s = 'Editing is under construction and certain properties may not yet be edit enabled.  For full editing use our Freebase domain found ' 
    s += '<a href="http://www.bioventurist.freebase.com/view/guid/'+guid+'" target="_blank">here</a>. '
    s += '(You may need to register for a Freebase account.)'
    $("#"+html_id).append(s);   
}

// Return an ordered array (ascending) of the top elements size(numOfElements)
function getOrder(array, numOfElements){
    if(numOfElements>array.length){
        numOfElements = array.length;
    }
    var ordered = new Array(numOfElements);
    var isChosen = new Array(array.length);
    for(var i=0; i<array.length; i++){
        isChosen[i]=false;
    }
    
    for(var i=0; i<numOfElements; i++){
        var max = 0;
        var index = -1;
        for(var j in array){
            if(array[j]>max && !isChosen[j]){
                max = array[j];
                index = j;
            }
        }       
        if(index<0){
            var foundVal = false;
            for(var j in isChosen){
                if(!isChosen[j] && !foundVal){
                    index = j;
                    isChosen[j] = true;
                    foundVal = true;
                }
            }
        } else {
            isChosen[index] = true;
        }
        ordered[i] = index;
    }
    return ordered;
}

function createTopic(name,type) {
    var name = name.replace("/","")
    var postCommand ='/create_topic/';
    //console.dir(name + ','+ type);
    var objects = new Object();

    var types = '[';
    for (var i=0; i<type.length; i++){
        types += '"'+type[i]+'"';
        types += (i==type.length-1 ? '' : ',');
    }
    types += ']';
    //type = '["/user/bioventurist/default_domain/science_or_technology_company","/business/company","/business/employer"]' 
    
    objects['topic_type'] = types;

    var topic_id = null;        
    var html = $.ajax({
            type: "POST",
            url: postCommand+name +'/',
            data: objects,
            async: false,
            success: function(m) {
            /*  if (console && console.log) {
                    console.log(m);
                }
                
                */
                var m_obj = JSON.parse(m).q1.result;
                topic_id = m_obj.id;
                return topic_id;
            
            },
            error: function(m) {
                return null;
            },
            dataType: "text",
            cache: false
        }); 
    return topic_id;
}

function link_type(name, type_current, type_new) {
    var postCommand ='/link_type/';
    
    var objects = new Object();
    objects['name'] = name;
    objects['type_current'] = type_current;
    objects['type_new'] = type_new;
    
    $.ajax({
            type: "POST",
            url: postCommand,
            data: objects,
            success: function(m) {
                /*if (console && console.log) {
                    console.log(m);
                }*/
            },
            error: function(m) {
            },
            dataType: "text",
            cache: false
        }); 
}
